package com.project.webapp.action.backend.basic;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts2.ServletActionContext;

import com.project.dao.bean.Article;
import com.project.dao.bean.Menu;
import com.project.service.backend.basic.IMenuService;
import com.project.service.backend.basic.IPaperService;
import com.project.webapp.action.BaseAction;

/**
 * 后台 新闻信息管理 Action
 * @author Sn
 *
 */
public class PaperAction extends BaseAction {

	/**
	 * 序列化版本号
	 */
	private static final long serialVersionUID = 1L;
	private static final String ADD_MENU = "addArticle";
	private String operateResult = "";
	private IPaperService paperService;
	private Article article;
	List<Article> articleList;
	private JSONArray jsonArray;
	private IMenuService menuService;
	
	private File uploadFile;  
    private String uploadFileFileName;

	@Override
	public String execute() throws Exception 
	{
		article = new Article();
		if (articleList != null && articleList.size() > 0) 
		{
			articleList.clear();
		}
		
		return this.query();
	}

	public String showAdd() 
	{
		article = new Article();
		operateResult = "";
		this.getTree();
		return SUCCESS;
	}

	/**
	 * 
	 * <pre>
	 * 查询
	 * </pre>
	 * 
	 * @return
	 */
	public String query() 
	{
		try 
		{
			operateResult = "";
			
			if (article == null) 
			{
				article = new Article();
			}
			
			articleList = paperService.findPaperBypg(article);

		} catch (Exception e)
		{
			e.printStackTrace();
		}

		return SUCCESS;
	}

	/**
	 * 
	 * <pre>
	 * 删除
	 * </pre>
	 * 
	 * @return
	 */
	public String delete() 
	{
		HttpServletRequest req = ServletActionContext.getRequest();
		String article_id = req.getParameter("article_id");
		try 
		{
			article.setArticle_id(article_id);

			paperService.delete(article);
			articleList = paperService.findPaperBypg(article);
			operateResult = "suc";
			
		} catch (Exception e) 
		{
			e.printStackTrace();
			operateResult = "fail";
		}
		return SUCCESS;
    }

	public String dao()
	{
    	String directory = "/upload/role";  
        String targetDirectory = ServletActionContext.getServletContext().getRealPath(directory);  
        //生成上传的文件对象   
        File target = new File(targetDirectory,uploadFileFileName);  
        //如果文件已经存在，则删除原有文件   
        if(target.exists())
        {  
            target.delete();  
        }  
        
        try 
        {  
        	//复制file对象，实现上传   
            FileUtils.copyFile(uploadFile, target);  
              
        } catch (IOException e) 
        {  
            e.printStackTrace();  
            operateResult = "faill";
        }  
        
        loadRoleInfo(uploadFileFileName);  
        operateResult = "succ";
    	return ADD_MENU;
    }
	
	public void loadRoleInfo(String uploadFileFileName)
	{  
		
        String directory = "/upload/role";   
        String targetDirectory = ServletActionContext.getServletContext().getRealPath(directory);  
        File target = new File(targetDirectory,uploadFileFileName);  
          
        try
        {  
            FileInputStream fi = new FileInputStream(target);  
            HSSFWorkbook wb = new HSSFWorkbook(fi); // 读取excel工作簿
			HSSFSheet sheet = wb.getSheetAt(0); // 读取excel的sheet，0表示读取第一个、1表示第二个.....
			
			for (int ii = 1; ii < sheet.getLastRowNum()+1; ii++) 
			{
				HSSFRow row = sheet.getRow(ii); // 取出sheet中的某一行数据
				if (row != null) 
				{
					// 获取该行中总共有多少列数据row.getLastCellNum()
					List<String> list = new ArrayList<String>();
					String str = null;
					for (int j = 0; j < row.getLastCellNum(); j++) 
					{
						HSSFCell cell = row.getCell((short) j); // 获取该行中的一个单元格对象
						// 判断单元格数据类型，这个地方值得注意：当取某一行中的数据的时候，需要判断数据类型，否则会报错
						// java.lang.NumberFormatException: You cannot get a string
						// value from a numeric cell等等错误
						if(null!=cell)
						{
							if (cell.getCellType() == 0) 
							{
								Long l= Math.round(cell.getNumericCellValue());
								str = l.toString();
								
							} else 
							{
								str = cell.getStringCellValue();
							}
						}else
						{
							cell = row.createCell((short)j);
							cell.setCellType(HSSFCell.CELL_TYPE_STRING);
							cell.setCellValue("");
							str = "";
						}
						list.add(str);
					}
					if(null==list.get(0)||"".equalsIgnoreCase(list.get(0)))
					{
						break;
					}
					
					System.out.println(list.size());
					System.out.println(list);
					Article article = new Article();
					article.setOrg_name(list.get(0));
					article.setCourse_contacts(list.get(1));
					article.setTel(list.get(2));
					article.setTel_other(list.get(3));
					article.setArea(list.get(4));
//					article.setMenu_code(list.get(5));
					article.setCourse_address(list.get(10));
					article.setArticle_content(list.get(11));
					article.setCourse_type(list.get(13));
					article.setTime_type(list.get(14));
					String weeks = list.get(15);
					String week = "";
					for(Integer i = 0;i<weeks.length();i++)
					{
						String b = weeks.substring(i, i+1);
						if(b.equals("1"))
						{
							week = week+i.toString()+",";
						}
					}
					
					if(week.length()!=0)
					{
						article.setCourse_week(week.substring(0,week.length()-1));
					}
					
					String times = list.get(23);
					String time = "";
					for(Integer i = 0;i<times.length();i++)
					{
						String b = times.substring(i, i+1);
						if(b.equals("1"))
						{
							time = time+i.toString()+",";
						}
					}
					
					if(time.length()!=0)
					{
						article.setCourse_time(time.substring(0,time.length()-1));
					}
					article.setCourse_fee(list.get(16));
					article.setArticle_title(list.get(17));
					article.setPic_link(list.get(18));
					
					String menu = list.get(5);
		    		for (String menu_id : menu.split("；"))
		    		{
		    			System.out.println("menuid~~~~~~~~~"+menu_id);
		    			article.setMenu_code(menu_id);
		    			paperService.saveExl(article);
					}
					
					list.clear();
				}
			}
        }catch(IOException e)
        {  
            e.printStackTrace();  
        } catch (Exception e) 
        {
			e.printStackTrace();
		}  
    }  

    /**
     * 
     * <pre>
     * 编辑
     * </pre>
     *
     * @return
     * @throws Exception 
     */
	public String edit() throws Exception 
	{
		HttpServletRequest req = ServletActionContext.getRequest();
		if (article == null) 
		{
			article = new Article();
		}
		
		this.getTree();
		operateResult = "";
		String article_id = req.getParameter("article_id");
		article.setArticle_id(article_id);
		article = paperService.getArticleById(article);
        
        if(null!=article.getArea() && !"".equalsIgnoreCase(article.getArea())&&article.getArea().length()==4)
        {
        	String area = article.getArea();
        	article.setArea_s(area.substring(0,2));
        	article.setArea_e(area.substring(2,4));
        }
        
        if(null!=article.getCourse_week()&&!"".equalsIgnoreCase(article.getCourse_week()))
        {
	        String[] week = article.getCourse_week().split(",");
	        List<String> weeks = new ArrayList<String>();
	        for (String ww : week) 
	        {
				weeks.add(ww.trim());
			}
			System.out.println(weeks+"week");
	        article.setWeekList(weeks);
        }
        
        if(null!=article.getCourse_time()&&!"".equalsIgnoreCase(article.getCourse_time()))
        {
	        String[] time = article.getCourse_time().split(",");
	        List<String> times = new ArrayList<String>();
	        for (String tt : time) {
				times.add(tt.trim());
			}
	        System.out.println(times+"time");
	        article.setTimeList(times);
        }
        return SUCCESS;
    }

	/**
	 * 
	 * <pre>
	 * 保存
	 * </pre>
	 * 
	 * @return
	 */
	public String save() 
	{
		try 
		{
			String list = article.getMenu_ids();
    		article.setArea(article.getArea_s()+article.getArea_e());
			for (String menu_id : list.split(",")) 
			{
				System.out.println("menuid~~~~~~~~~" + menu_id);
				article.setMenu_id(menu_id);
				paperService.save(article);
			}
			operateResult = "suc";
			
		} catch (Exception e) 
		{
			e.printStackTrace();
			operateResult = "fail";
		}
		article = new Article();
		return ADD_MENU;
	}

	public String save1() 
	{
		try 
		{
			String a = article.getMenu_ids();
			if (a.contains(",")) 
			{
				a = a.substring(0, a.indexOf(","));
			}
			
			System.out.println("menuid~~~~~~~~~" + a);
			article.setMenu_id(a);
    		article.setArea(article.getArea_s()+article.getArea_e());
			paperService.update(article);
			operateResult = "suc";
			
		} catch (Exception e) 
		{
			e.printStackTrace();
			operateResult = "fail";
		}
		article = new Article();
		return ADD_MENU;
	}

	public void getTree() 
	{
		try 
		{
			List<Menu> menuList = null;
			List<Map<String, String>> jsonDataSourceList = new ArrayList<Map<String, String>>();
			menuList = menuService.findMenuForTree();
			if (menuList != null && menuList.size() > 0) 
			{
				for (Menu m : menuList) 
				{
					Map<String, String> menuVoMap = new HashMap<String, String>();
					menuVoMap.put("id", m.getMenuId());
					menuVoMap.put("pId", (m.getParentId() == null || "".equals(m.getParentId())) ? "1" : m.getParentId());
					menuVoMap.put("name", m.getMenuName());
					menuVoMap.put("open", "false");
					jsonDataSourceList.add(menuVoMap);
				}
			}
			jsonArray = JSONArray.fromObject(jsonDataSourceList);
			JSONObject json = new JSONObject();
			json.put("id", 1);
			json.put("name", "根菜单");
			json.put("pId", 0);
			json.put("isParent", true);
			json.put("open", true);
			jsonArray.add(json);
		} catch (Exception e) 
		{
			e.printStackTrace();
		}
	}
	
    public File getUploadFile() {
		return uploadFile;
	}

	public void setUploadFile(File uploadFile) {
		this.uploadFile = uploadFile;
	}

	public String getUploadFileFileName() {
		return uploadFileFileName;
	}

	public void setUploadFileFileName(String uploadFileFileName) {
		this.uploadFileFileName = uploadFileFileName;
	}
	
	public static String getAddMenu() {
		return ADD_MENU;
	}
	
	public void setPaperService(IPaperService paperService) {
		this.paperService = paperService;
	}

	public Article getArticle() {
		return article;
	}

	public void setArticle(Article article) {
		this.article = article;
	}

	public List<Article> getArticleList() {
		return articleList;
	}

	public void setArticleList(List<Article> articleList) {
		this.articleList = articleList;
	}

	public void setMenuService(IMenuService menuService) {
		this.menuService = menuService;
	}

	public String getOperateResult() {
		return operateResult;
	}

	public void setOperateResult(String operateResult) {
		this.operateResult = operateResult;
	}

	public JSONArray getJsonArray() {
		return jsonArray;
	}

	public void setJsonArray(JSONArray jsonArray) {
		this.jsonArray = jsonArray;
	}

	public static long getSerialversionuid() {
		return serialVersionUID;
	}

	public IPaperService getPaperService() {
		return paperService;
	}

	public IMenuService getMenuService() {
		return menuService;
	}

}
